const categoryModel = require('../model/CategoryModel')
let {SUCCESS_RESPONSE} = require('../config/index')
const executeSql = require('../utils/query.js')


exports.getCategoryList = async (req, res) => {

    // 所有的查询字符串req.query接收的值都是字符串string类型
    let {
        page = 1,
        pageSize = 5,
        category_name,
        is_show,
        start_date,
        end_date,
    } = req.query
    // 1. 编写sql语句查询数据（model层）
    // 2. 查询数据
    let category = await categoryModel.selectCategoryPage({
        page,
        pageSize,
        category_name,
        is_show,
        start_date,
        end_date,
    })
    // 查询符合条件的总记录数
    let count = await categoryModel.selectALlCategoryCount({
        category_name,
        is_show,
        start_date,
        end_date,
    })
    // 3. 返回
    res.json({
        code: '00000',
        data: {
            count, // 总记录数
            category, // 分页数据
        },
        msg: '获取分类成功',
    })
}

exports.getOneCategory = async (req, res) => {
    let {category_id} = req.query
    // 1. 编写sql语句查询数据（model层）,// 2. 查询
    let category = await CategoryModel.find(category_id)
    // 3. 返回
    res.json({
        code: '00000',
        data: category,
        msg: '获取分类成功',
    })
}

exports.checkUpdateCategoryName = async (req, res) => {

    let {category_id, category_name} = req.query

    const result = await categoryModel.checkUpdateCategoryName(
        category_id,
        category_name
    )
    console.log('1111' + result)
    if (!result) {
        // 有重名的
        res.json({
            code: '00009',
            data: {},
            msg: '编辑分类名重复',
        })
    } else {
        // 可用
        res.json({
            code: '00000',
            data: {},
            msg: '编辑分类名可用',
        })
    }
}

exports.addCategory = async (req, res) => {

    let is_repeat = await categoryModel.checkAddCategoryName(req.body.category_name)
    if (is_repeat) {
        let result = await categoryModel.insertCategory(req.body)
        if (result.affectedRows > 0) {
            res.json({
                code: '00000',
                data: {},
                msg: 'Add category success',
            })
        } else {
            res.json({
                code: '00005',
                data: {},
                msg: 'Add category fail',
            })
        }
    } else {
        res.json({
            code: '00008',
            data: {},
            msg: 'Add category fail this category already exists',
        })
    }
}

exports.delCategory = async (req, res) => {

    let {category_id} = req.query
    let result = await categoryModel.delCategoryById(category_id)
    if (result.affectedRows > 0) {
        res.json({
            code: '00000',
            data: {},
            msg: 'Delete category success',
        })
    } else {
        res.json({
            code: '00006',
            data: {},
            msg: 'Delete category fail',
        })
    }
}

exports.delBatchCategory = async (req, res) => {
    let {category_ids} = req.body
    let result = await categoryModel.delBatchCategory(category_ids)
    if (result.affectedRows > 0) {
        res.json({
            code: '00000',
            data: {},
            msg: 'Batch delete category success',
        })
    } else {
        res.json({
            code: '00007',
            data: {},
            msg: 'Batch delete category fail',
        })
    }
}

exports.getCategoryById = async (req, res) => {
    try {
        const {category_id} = req.query;
        const category = await categoryModel.selectCategoryById(category_id);

        if (!category || category.length === 0) {
            return res.json({
                code: '40004',
                data: null,
                msg: 'Category not found',
            });
        }

        // 直接返回第一个对象而不是数组
        res.json({
            code: '00000',
            data: category[0],  // 直接返回对象而不是数组
            msg: 'Get category success',
        });
    } catch (error) {
        res.status(500).json({
            code: '50000',
            data: null,
            msg: 'Server error',
        });
    }
}

exports.updateCategory = async (req, res) => {
    let result = await categoryModel.updateCategoryById(req.body)
    if (result.affectedRows > 0) {
        res.json({
            code: '00000',
            data: {},
            msg: 'Update category success',
        })
    } else {
        res.json({
            code: '00010',
            data: {},
            msg: 'Update category fail',
        })
    }
}

exports.searchCategory = async (req, res) => {
    let {category_name, is_show, start_date, end_date} = req.query
    let sql = `select * from category where 1 `
    //  根据查询条件，有传条件，动态的拼接sql语句
    if (category_name) {
        sql += ` and category_name like '%${category_name}%'`
    }
    if (is_show) {
        sql += ` and is_show = ${is_show}`
    }

    if (start_date && !end_date) {
        sql += ` and add_date > ${start_date}`
    }

    if (!start_date && end_date) {
        sql += ` and add_date < ${end_date}`
    }

    if (start_date && end_date) {
        sql += ` and add_date between ${start_date} and ${end_date}`
    }

    let data = await executeSql(sql)
    res.json(data)
}

exports.getAllCategory = async (req, res) => {
    let result = await categoryModel.selectAllCategory()
    res.json(SUCCESS_RESPONSE(result))
}
